package risk.control.project.task;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import risk.control.project.config.constant.FilePath;
import risk.control.project.entity.repository.BranchBean;
import risk.control.project.mapper.branch.BranchMapper;
import risk.control.project.poi.branch.BranchData;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 读取网点文件，入库
 */
public class BranchBatchTask implements Job {

    private static final Logger logger = LoggerFactory.getLogger(BranchBatchTask.class);


    // 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
    private static final int BATCH_COUNT = 100;
    // 缓存的数据
    private final List<BranchData> cacheDataList = new ArrayList<>(BATCH_COUNT);


    @Qualifier("MainSqlSessionFactory")
    private final SqlSessionFactory sqlSessionFactory;


    public BranchBatchTask(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        //每次读取指定文件夹下的文件，入库，删除文件
        String folderPath = FilePath.UPLOAD_BRANCH_FOLDER;
        // 获取文件夹对象
        File folder = new File(folderPath);
        // 检查路径是否存在且是一个文件夹
        if (!folder.exists() || !folder.isDirectory()) {
            return;
        }
        // 获取文件夹中的所有文件
        File[] files = folder.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        //处理过程->每次拿一个文件处理
        File file = files[0];
        String absolutePath = file.getAbsolutePath();
        //开始读取文件
        logger.warn("开始读取文件:{}", absolutePath);
        EasyExcel.read(absolutePath, BranchData.class, new ReadListener<BranchData>() {
            @Override
            public void invoke(BranchData data, AnalysisContext analysisContext) {
                // 每读取一行数据会调用此方法，自动跳过表头
                cacheDataList.add(data);
                // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
                if (cacheDataList.size() >= BATCH_COUNT) {
                    saveData();
                    cacheDataList.clear();//存储完成清理 list
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                // 所有数据解析完成了,确保最后遗留的数据也存储到数据库
                saveData();
                cacheDataList.clear();//存储完成清理 list
                //处理后删除文件
                boolean deleted = file.delete();
                logger.warn("处理完成，删除文件{}", file.getName());
            }
        }).sheet().doRead();
    }

    // 存储数据库
    private void saveData() {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            BranchMapper mapper = session.getMapper(BranchMapper.class);
            List<BranchBean> fullBranchList = new ArrayList<>();
            //数据转换
            for (BranchData data : cacheDataList) {
                BranchBean branchBean = new BranchBean();
                String branchName = data.getBranchName();
                String branchAddress = data.getBranchAddress();
                String bankName = data.getBankName();
                String belongDistricts = data.getBelongDistricts();

                branchBean.branchId = DigestUtils.md5Hex(branchName);
                branchBean.branchName = branchName;
                branchBean.branchAddress = branchAddress;
                branchBean.bankName = bankName;
                branchBean.belongDistricts = belongDistricts;

                //添加进集合
                fullBranchList.add(branchBean);
            }
            mapper.addBranchBatch(fullBranchList);
        }


    }
}
